var mysql = require('mysql');
var fs = require('fs');

class TMySql{
    constructor(){
        this.dbs ={
            mysqlDemo:{
                host:"tjiot.hhdata.cn" ,
                port:53306,
                uid:"dbdemo" ,
                pwd:"dbdemo" ,
                db :"dbdemo" ,
                sqlPath:"D:/project/c6241016/c6241016_93251021/sqls"
            },
            remoteMedice:{
                host:"192.168.11.234" ,
                port:53306,
                uid:"dbdemo" ,
                pwd:"dbdemo" ,
                db  :"medince" ,
                sqlPath:"D:/project/c6241016/c6241016_93251021/sqls"
            }
        }
    }

    getConnection(appId ){
        var me = this;
        return new Promise((success, faild)=>{
            try{
                if( me.dbs[appId] ){
                    var dbInfo = me.dbs[appId];
                    if( !dbInfo.pool){
                        dbInfo.pool = mysql.createPool({
                            host: dbInfo.host ,
                            port: dbInfo.port ,
                            user: dbInfo.uid ,
                            password: dbInfo.pwd ,
                            database: dbInfo.db,
                            connectionLimit:100,
                            multipleStatements:true
                        });
                    }                        
                    dbInfo.pool.getConnection( function (err, conn) {
                        if( conn &&conn!=null){
                            conn.config.queryFormat = function (query, values) {
                                if (!values) return query;
                                return query.replace(/\:(\w+)/g, function (txt, key) {
                                        if (values.hasOwnProperty(key)) {
                                        return this.escape(values[key]);
                                        }
                                        return txt;
                                    }.bind(this));
                            };
                            success(conn);
                        }
                        else{
                            success({
                                err:"db config info is error."
                            })
                        }
                    })
                }
                else{
                    success({
                        err:"appId is error"
                    })
                }
            }
            catch(er){
                console.log(er);
                success();
            }
        })
    }
    getSql ( appId , key   ){
        var res = "";
        try{
            if( me.dbs[appId] ){
                var rootPath = me.dbs[appId].sqlPath;
                var fullFn = rootPath +"/" + key;
                fullFn = fullFn.repeat("//" , "/");
                if( fullFn.indexOf(".txt")<0){
                    fullFn += ".txt";
                }
                var flag = fs.existsSync(fullFn);
                if( flag){
                    res = fs.readFileSync(fullFn);
                }
            }
        }
        catch(er){
            console.log(er);
        }
        return res;
    }
    query(appId , key , ps ){
        var me = this;
        return new Promise((success, faild)=>{
            try{
                if( me.dbs[appId] ){
                    var sql = me.getSql(appId , key);
                    if( sql == ""){
                        success({
                            "err":"key is error."
                        })
                    }
                    else {
                        me.getConnection( appId).then(  function( conn ){
                            if( conn.err){
                                success(conn);
                            }
                            else{
                                //var s = resConn.conn.format(sql , ps);
                                //console.log(s);
                                conn.query(sql, ps, function (errQuery, results, fields) {
                                    conn.release();
                                    if (errQuery) {
                                        var s = resConn.conn.format(sql , ps);
                                        res.error = errQuery;
                                        console.log(errQuery, s, ps);
                                        success(null)
                                    } else {
                                        success(results);
                                    }
                                })
                            }
                        });
                    }
                }
                else{
                    success({
                        err:"appId is error"
                    })
                }
            }
            catch(er){
                console.log(er);
                success();
            }
        })
    }
    regist2Svr(webSvr){
        try{
            var me = this;
            var key = ['db' , 'mysql' , 'query'].join("/")
            webSvr.actionHandler[key] = function(result , req , resp){
                var appId = result.ps.appId ;
                var key = result.ps.key ;
                var psJson = result.ps.psJson ;
                var ps = JSON.parse(psJson);
                me.query( appId , key , ps ).then(res=>{
                    result.result = res;
                    resp.send(JSON.stringify((result)));
                });
            }
        }
        catch(Exce){
            console.log(Exce)
        }
    }
}



module.exports = {
    TMySql : TMySql
}